<template>
  <div :class="$style.listen">
    <ContentWrap>
      <!-- <div :class="$style.query">
        <p>坐席展示方式：</p>
        <el-radio-group v-model="viewType">
          <el-radio label="table">坐席列表</el-radio>
          <el-radio label="chart">坐席图表</el-radio>
        </el-radio-group>
      </div> -->
      <FormContainer :column="4">
        <el-form
          ref="queryForm"
          :model="queryData"
          :rules="queryRules"
          label-width="80px"
        >
          <el-form-item prop="workno" label="坐席标识">
            <el-select
              v-model.trim="queryData.workno"
              clearable
              filterable
              placeholder="请输入坐席标识"
              :remote-method="getStaffInfo"
              remote
            >
              <el-option v-for="(a,i) in agentList" :key="i" :value="a.platformNo" :label="`${a.staffName}(${a.accountNo})`"></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item prop="organization" label="组织">
            <el-select
              v-model="queryData.organization"
              clearable
              filterable
              placeholder="请选择组织"
            >
              <el-option
                v-for="(o, i) in orgList"
                :key="i"
                :value="o.groupNo"
                :label="o.groupName"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item prop="skillid" label="技能组">
            <el-select
              v-model="queryData.skillid"
              clearable
              filterable
              placeholder="请选择技能组"
              @change="changeHandle"
            >
              <el-option
                v-for="(g, i) in skillGroupList"
                :key="i"
                :value="g.skillNo"
                :label="g.skillName"
              />
            </el-select>
            <!-- <el-select
              v-model="queryData.skillid"
              clearable
              filterable
              placeholder="请选择技能组"
            >
              <el-option
                v-for="(g, i) in skillList"
                :key="i"
                :value="g.id"
                :label="g.name"
              />
            </el-select> -->
          </el-form-item>
          <el-form-item prop="status" label="坐席状态">
            <el-select
              v-model="queryData.status"
              clearable
              filterable
              placeholder="请选择坐席状态"
            >
              <el-option
                v-for="(s, i) in statusList"
                :key="i"
                :value="s.value"
                :label="s.label"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <div class="button-container" style="padding:0;">
              <Button type="primary" :loading="loading" enter @click="queryHandle">查询</Button>
            </div>
          </el-form-item>
        </el-form>
      </FormContainer>
      <div class="button-container" :class="$style.btn">
        <!-- 发送消息、监听通话、加入通话、接管通话、强制示闲、强制示忙、强制签出 -->
        <!-- <Note :agent-ids="selected.map(e=>e.workno)"></Note> -->
        <Button type="primary" @click="checkListenOrInsert('listen')">{{ listenText }}</Button>
        <Button type="primary" @click="checkListenOrInsert('insert')">{{ insertText }}</Button>
        <Button type="primary" @click="()=>checkSelect(interceptHandle)">接管通话</Button>
        <Button type="primary" @click="()=>checkSelect(forceFreeHandle)">强制示闲</Button>
        <Button type="primary" @click="()=>checkSelect(forceBusyHandle)">强制示忙</Button>
        <Button type="primary" @click="()=>checkSelect(forceSignOutHandle)">强制签出</Button>
      </div>
      <div>
        <Table :data="agentDetail" :filter-fun="filterSeatList">
          <template v-slot:body="data">
            <SeatChartList v-model="selected" :multiple="false" :data="data" />
          </template>
        </Table>
      </div>
    </ContentWrap>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import FormContainer from '@/components/FormContainer'
import SeatChartList from './components/SeatChartList'
// import Note from './components/Note'
import Table from './components/Table'
import { mapGetters } from 'vuex'
// import { getBusinessAll } from '@/api/business'
import { getSkillGroup, pageSkillMembers } from '@/api/skillGroup'
import { getStaffInfo } from '@/api/staffInfo'
import { filtersRaw, pageRequsetBody } from '@/utils'
export default {
  name: 'Listen',
  components: {
    ContentWrap,
    FormContainer,
    SeatChartList,
    Table
    // Note
  },
  data() {
    return {
      loading: false,
      // 坐席标识列表
      agentList: [],
      // 转坐席
      // viewType: 'table', // 显示方式
      // 选中坐席
      selected: [],
      // 坐席查询数据
      queryData: {
        workno: '',
        // organization: '',
        skillid: '',
        status: ''
      },
      queryRules: {
        skillid: [{ required: true, message: '请选择技能', trigger: 'change' }]
      },
      // 分支机构列表
      orgList: [],
      // 客服总列表
      agentDetail: [],
      // 业务系统技能组
      skillGroupList: [],
      // 0: '未知',
      // 1: '签入',
      // 2: '签出',
      // 3: '示忙',
      // 4: '空闲',
      // 5: '整理',
      // 6: '空闲',
      // 7: '通话',
      // 8: '休息'
      statusList: [
        {
          value: '',
          label: '全部'
        },
        // {
        //   value: 1,
        //   label: '签入'
        // },
        // {
        //   value: 2,
        //   label: '签出'
        // },
        {
          value: 3,
          label: '示忙'
        },
        {
          value: 4,
          label: '示闲'
        },
        {
          value: 7,
          label: '通话'
        }
        // {
        //   value: 8,
        //   label: '休息'
        // }
      ],
      // 当前选中的技能
      id: '',
      // 当前监听坐席
      listenWorkNo: null,
      // 当前加入的通话坐席
      insertWorkNo: null
    }
  },
  computed: {
    ...mapGetters(['agentState', 'agentid', 'skillList']),
    // 控制除发送消息外的按钮是否可用
    isDisabled() {
      return this.selected.length !== 1
    },
    // 监听按钮
    listenText() {
      return this.listenWorkNo === null ? '监听通话' : '退出监听'
    },
    // 加入通话按钮
    insertText() {
      return this.insertWorkNo === null ? '加入通话' : '退出通话'
    }
  },
  created() {
    if (!this.agentState.sign && !this.$dev) {
      this.$router.replace({ name: 'Index' })
      this.$message.error('请先签入！')
      return
    }
    this.getSkillGroup()
    this.getStaffInfo('') // 获取20个职员信息
  },
  methods: {
    // 更新选中的技能id
    changeHandle(v) {
      for (const g of this.skillGroupList) {
        if (g.skillNo === v) {
          this.id = g.id
          break
        }
      }
    },
    queryHandle() {
      this.loading = true
      this.$refs.queryForm
        .validate()
        .then(() => {
          return Promise.all([this.getAgentDetailList(), this.pageSkillMembers()]).then(res => {
            const vdnData = res[0].data.agentDetail
            const staffData = res[1].data.records
            this.agentDetail = this.concatData(vdnData, staffData)
            // currentStateReason: 0
            // currentstatetime: 45
            // name: "50004"
            // phonenumber: "6019"
            // status: 4
            // workno: "50004"

            //       {
            //   "accountNo": "string",
            //   "id": "string",
            //   "organization": "string",
            //   "platformNo": "string",
            //   "skillId": "string",
            //   "staffCode": "string",
            //   "staffName": "string",
            //   "state": 0
            // }
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 合并vdn与员工数据
    concatData(vdnData, staffData) {
      for (const v of vdnData) {
        for (const s of staffData) {
          if (v.workno === s.platformNo) {
            for (const key of Object.keys(s)) {
              v[key] = s[key]
            }
            continue
          }
        }
      }
      return vdnData
    },
    // 根据技能查坐席数据
    getAgentDetailList() {
      this.agentDetail = []
      return this.$cps
        .queryAgentBySkill(this.queryData.skillid)
        // .then(res => {
        //   this.agentDetail = res.data.agentDetail
        // })
    },
    // 根据条件筛选
    filterSeatList(data) {
      const { workno, status } = this.queryData
      if (workno === '' && status === '') {
        return data
      }
      if (status === '' && workno !== '') {
        return data.filter(e => e.workno === workno)
      }
      if (status !== '' && workno === '') {
        return data.filter(e => e.status === status)
      }
      return data.filter(e => e.status === status && e.workno === workno)
    },

    // 提示
    checkSelect(fun) {
      if (this.selected.length === 1) {
        return fun().then(() => {
          // this.queryHandle()
          return Promise.resolve()
        })
      }
      if (this.selected.length === 0) {
        this.$message.error('请选择坐席！')
        return Promise.reject()
      }
      if (this.selected.length > 1) {
        this.$message.error('只能选择一个坐席！')
        return Promise.reject()
      }
    },
    // 检查监听或加入通话
    checkListenOrInsert(type) {
      if (type === 'listen') {
        if (this.listenWorkNo === null) {
          return this.checkSelect(this.listenHandle)
        } else {
          return this.cancelHandle(type)
        }
      } else {
        if (this.insertWorkNo === null) {
          return this.checkSelect(this.joinHandle)
        } else {
          return this.cancelHandle(type)
        }
      }
    },
    // 监听通话
    listenHandle() {
      return this.$cps.listen(this.selected[0].workno).then(res => {
        this.listenWorkNo = this.selected[0].workno
        this.$message.success('正在监听！')
      })
    },
    // 加入通话
    joinHandle() {
      return this.$cps.insert(this.selected[0].workno).then(res => {
        this.insertWorkNo = this.selected[0].workno
        this.$message.success('加入通话成功！')
      })
    },
    // 接管通话
    interceptHandle() {
      return this.$cps.intercept(this.selected[0].workno).then(res => {
        this.$message.success('接管通话成功！')
      })
    },
    // 取消监听或插入
    cancelHandle(type) {
      const { listenWorkNo, insertWorkNo } = this
      const value = type === 'listen' ? listenWorkNo : insertWorkNo
      return this.$cps.cancel(value).then(res => {
        type === 'listen' ? this.listenWorkNo = null : this.insertWorkNo = null
        this.$message.success('退出成功！')
      })
    },
    // 强制示闲
    forceFreeHandle() {
      return this.$cps.agentForceIdle(this.selected[0].workno).then(res => {
        this.$message.success('强制示闲成功！')
      })
    },
    // 强制示忙
    forceBusyHandle() {
      return this.$cps.agentForceBusy(this.selected[0].workno).then(res => {
        this.$message.success('强制示忙成功！')
      })
    },
    // 强制签出
    forceSignOutHandle() {
      return this.$cps.agentForceOut(this.selected[0].workno).then(res => {
        this.$message.success('强制签出成功！')
      })
    },
    // 获取技能组
    getSkillGroup() {
      return getSkillGroup().then(res => {
        this.skillGroupList = res.data
      })
    },
    // 获取员工列表信息
    getStaffInfo(v) {
      const data = {
        filtersRaw: [],
        pageFlag: true
      }
      // 验证是名字还是拼音
      if (/^[a-zA-Z]+$/.test(v)) {
        data.filtersRaw.push(filtersRaw('accountNo', v, 'like'))
      } else {
        data.filtersRaw.push(filtersRaw('staffName', v, 'like'))
      }
      getStaffInfo(pageRequsetBody(data)).then(res => {
        this.agentList = res.data.records
      })
    },
    // 获取指定技能下的员工信息
    pageSkillMembers() {
      const data = {
        pageFlag: false
      }
      return pageSkillMembers(this.id, pageRequsetBody(data))
    }
  }
}
</script>
<style lang="scss" module>
@import "@/styles/mixin.scss";
.listen {
  .query {
    @include flex($align: center);
    padding: 20px 0;
    & > p {
      margin: 0 10px 0 0;
      padding: 0;
    }
  }
  .btn {
    @include flex($justify:flex-end);
    margin: 0;
    padding: 10px 0;
  }
}
</style>
